﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;

namespace Payment.SqlHelp
{
    /// <summary>
    /// sql说明书xml
    /// </summary>
    public class SqlHelpXmlDocument
    {
        static string GetShuxing(string xml)
        {
            XmlDocument xd = new XmlDocument();
            xd.LoadXml(xml);
            foreach (XmlNode item in xd.GetElementsByTagName("References"))
            {
                var b = item.Attributes != null && item.Attributes["ExternalSource"].Value == "BuiltIns";
                if (b)
                {
                    return item.Attributes["Name"].Value;
                }
            }
            return "";
        }

        public static IEnumerable<SqlModel> GetSqlModels(string file)
        {
            XmlDocument xd = new XmlDocument();
            xd.Load(@"D:\Model.xml");

            XmlNodeList elementsByTagName = xd.GetElementsByTagName("Element");



            List<SqlField> fields = new List<SqlField>();
            foreach (XmlNode item in elementsByTagName)
            {
                //   获取列节点
                var b2 = item.Attributes != null && item.Attributes["Type"].Value == "SqlSimpleColumn";
                if (b2)
                {
                    //   获取列名字
                    var shuxingming = item.Attributes["Name"].Value;
                    var outerXml = item.OuterXml;
                    var leixing = GetShuxing(outerXml);

                    var field = new SqlField();
                    field.FieldName = shuxingming;
                    field.FieldType = shuxingming;


                    foreach (XmlNode item2 in elementsByTagName)
                    {
                        //   获取注释
                        var b = item2.Attributes != null && item2.Attributes["Type"].Value == "SqlExtendedProperty" && item2.Attributes["Name"].Value.Contains(shuxingming);

                        if (b)
                        {
                            field.FieldDocument = item2.InnerText;
                        }
                    }
                    fields.Add(field);
                }

            }

            var smList = fields.GroupBy(a => a.FieldName.Split('.')[1]).Select(a =>
            {
                var model = new SqlModel();
                model.ModelName = a.Key;
                foreach (var item in a)
                {
                    model.Fields.Add(item);
                }
                return model;
            }).ToList();


            return smList;
        }

    }
}